package com.pbase.data.http.upanddown;


import com.pbase.data.http.listener.OnDataRequestListenerWithProgress;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import io.reactivex.rxjava3.annotations.Nullable;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * 上传进度监听
 */
public class ProgressRequsetBody extends RequestBody {
    private RequestBody requestBody;
    private OnDataRequestListenerWithProgress listener;
    //包装完成的BufferedSink
    private BufferedSink bufferedSink;


    public ProgressRequsetBody(RequestBody requestBody,
                               OnDataRequestListenerWithProgress listener) {
        this.requestBody = requestBody;
        this.listener = listener;
    }

    @Override
    public long contentLength()  {

        try {
            return requestBody.contentLength();
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Nullable
    @Override
    public MediaType contentType() {
        return requestBody.contentType();
    }


    /**
     * 重写进行写入
     * @param sink BufferedSink
     * @throws IOException 异常
     */
    @Override
    public void writeTo(@NotNull BufferedSink sink) throws IOException {
        if (bufferedSink == null) {
            //包装
            Sink sk = sink(sink);
            bufferedSink = Okio.buffer(sk );
        }
        //写入
        requestBody.writeTo(bufferedSink);
        //必须调用flush，否则最后一部分数据可能不会被写入
        bufferedSink.flush();
    }


    /**
     * 写入，回调进度接口
     * @param sink Sink
     * @return Sink
     */
        private Sink sink(Sink sink) {
        return new ForwardingSink(sink) {
            //当前写入字节数
            long bytesWritten = 0L;
            //总字节长度，避免多次调用contentLength()方法
            long contentLength = 0L;

            @Override
            public void write(Buffer source, long byteCount) throws IOException {
                super.write(source, byteCount);
                if (contentLength == 0) {
                    //获得contentLength的值，后续不再调用
                    contentLength = contentLength();
                }
                //增加当前写入的字节数
                bytesWritten += byteCount;
                //回调
                if (  listener!=null) {
                    listener.onProgressChange(bytesWritten, contentLength);
                }
            }
        };
    }
}
